import { defineStore } from 'pinia'

export const cartStore = defineStore('cart', {
  state: () => ({
    cartItems: [],
    totalPrice: 0
  }),
  actions: {
    addToCart(dish) {
      // 检查是否已经在购物车中
      const existItem = this.cartItems.find(item => item.id === dish.id)
      
      if (existItem) {
        // 如果已存在，增加数量
        existItem.quantity += 1
      } else {
        // 如果不存在，添加到购物车
        this.cartItems.push({
          ...dish,
          quantity: 1
        })
      }
      
      // 更新总价
      this.calculateTotal()
    },
    
    removeFromCart(id) {
      const index = this.cartItems.findIndex(item => item.id === id)
      if (index !== -1) {
        this.cartItems.splice(index, 1)
        this.calculateTotal()
      }
    },
    
    updateQuantity(id, quantity) {
      const item = this.cartItems.find(item => item.id === id)
      if (item) {
        item.quantity = quantity
        this.calculateTotal()
      }
    },
    
    calculateTotal() {
      this.totalPrice = this.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    },
    
    clearCart() {
      this.cartItems = []
      this.totalPrice = 0
    }
  },
  getters: {
    getCartItems: (state) => state.cartItems,
    getCartCount: (state) => state.cartItems.reduce((count, item) => count + item.quantity, 0),
    getTotalPrice: (state) => state.totalPrice
  }
})